(function(){

	angular.module("webApp").controller('GoodsCtrl',GoodsCtrl);
	GoodsCtrl.$inject=['$scope','dataService','$rootScope','$location','sessionService','$timeout','helper','$window','cacheService'];
	function GoodsCtrl($scope,dataService,$rootScope,$location,sessionService,$timeout,helper,$window,cacheService) {
		  $scope.Popup="block";
		  $scope.conllection="default";
		  $scope.settings = {
		    enableFriends: true
		  };
		  $scope.itemAction=function(){
		    $scope.item_id = $location.search().item_id;
		    $scope.shop_id = $location.search().shop_id;
		    $scope.shop_name  = $location.search().shop_name;
		    $scope.review_num=5;//评论显示的条数
		    $scope.quantity=1;
		    $scope.skus_History=[];
		    $scope.review_Page_no=1;//查询评论第几页
		    $scope.review_Size=10;//查询评论的返回的最多条数
		    var query={};
		    query.query={item_id:$scope.item_id};
		    dataService.itemGet(query).then(function(result){
		    	$scope.item=result.items[0];
		  		$scope.item.quantity=1;
		  		$scope.skusPro={};
		  		$scope.skusProCopy=[];
		  		$scope.sku_info={};
		  		//保存的sku值
		  		$scope.Save_Sku={};
		  		async.map($scope.item.skus,function(sku,back){
		  			sku.sku_checked=null;
		  			var data={};
		  			data.Analysis=[];
		  			var key_find="";
		  			_.map(sku.sku_properties.split(";"),function(properties){
		  				var obj=[];
		  				if($.trim(properties)){
			  				var propertie= properties.split(":");
			  				key_find+=propertie[2]+":"+propertie[3]+";";
			  				obj.en=propertie[0]+":"+propertie[1];
			  				obj.ch=propertie[2]+":"+propertie[3];
			  				obj.ch_key=propertie[2];
			  				obj.ch_value=propertie[3];
			  				obj.sku_checked=null;
			  				if($scope.skusPro[propertie[2]]){
			  					if(_.indexOf($scope.skusPro[propertie[2]].array,propertie[3]) === -1){
			  						$scope.skusPro[propertie[2]].array.push(propertie[3]);
				  					$scope.skusPro[propertie[2]].not_cheked=[];
			  					}
			  				}else{
			  					$scope.skusPro[propertie[2]]={};
			  					$scope.skusPro[propertie[2]].array=[];
			  					$scope.skusPro[propertie[2]].array.push(propertie[3]);
			  					$scope.skusPro[propertie[2]].propertie_checked=null;
			  					$scope.skusPro[propertie[2]].typeName=propertie[2];
			  					$scope.skusPro[propertie[2]].not_cheked=[];
			  				}
			  				data.Analysis.push(obj);
		  				}
		  				
		  			});
		  			key_find= key_find.substring(0,key_find.length-1)
		  			// console.log(key_find.substring(0,key_find.length-1));
		  			$scope.sku_info[key_find]={};
		  			$scope.sku_info[key_find].sku_stocks=sku.sku_stocks;
		  			$scope.sku_info[key_find].status_id=sku.status_id;
		  			$scope.sku_info[key_find].sku_id=sku.sku_id;
		  			$scope.sku_info[key_find].sku_price=sku.sku_price;
		  			$scope.sku_info[key_find].sku_propertie=key_find;

		  			data.sku_properties=sku.sku_properties;
		  			data.sku_checked=null;
		  		    $scope.skusProCopy.push(data);
		  		    back(null,null);
		  		},function(e,r){

		  				// _.map($scope.skusPro,function(skusPro){
		  				// 	console.log(skusPro);
		  				// 	if(_.size(skusPro.array)==1){
		  				// 		skusPro.propertie_checked=skusPro.array[0];
		  				// 	}
		  				// })
		  			});
		  		if(!$scope.shop_id){
		  			dataService.storeOne($scope.item.partner_id).then(function(stores){
		  				$scope.shop_id=stores.store[0].store_id;
		  			});	
		  		}
		    	$scope.getFavorites();
		    	$scope.getReview();
		    	$scope.skuActionPrice();
		    	initSKU();
		    		$scope.$watch('skusPro',function(){
		  			$scope.getSkuPrice();
		  		},true)
				// $scope.cartAction();
		    });
		  }
	  	  $scope.getFavorites=function(){
	  	  	var data ={item_id:$scope.item.item_id};
	  	  		$rootScope.FavoritesGet().then(function(result){
	  	  			if(!result.Msg){
	  	  				_.map(result.Favorites,function(favorites){
	  	  					if(favorites.item_id==$scope.item_id){
	  	  						$scope.conllection="checked";
	  	  						$scope.Favorites=favorites;
	  	  					}
	  	  				});
	  	  			}
	  	  		});
	  	  }
	  	  $scope.getReview=function(){
	  	  	var query={page_no:$scope.review_Page_no,page_size:$scope.review_Size};
	  	  	query.query={item_id:$scope.item.item_id};
	  	  	dataService.reviewGet(query).then(function(result){
	  	  		if(result.Msg){
	  	  			helper.myAlert("error:"+result.Msg);
	  	  		}else{
	  	  			$timeout(function(){
	  	  			});
	  	  			$scope.reviews=result.review;
	  	  			if(!$scope.review_total_count){
	  	  				$scope.review_total_count=result.total_count;
	  	  			}
	  	  			_.map($scope.reviews,function(review){
	  	  				dataService.itemOne(review.partner_id).then(function(item){
	  	  					review.item=item;
	  	  				});
	  	  			})
	  	  		}
	  	  	});
	  	  }
	  	  $scope.setReviewpage=function(condition){
	  	  	if(condition=='-'){
	  	  		$scope.review_Page_no-=1;
	  	  		$scope.getReview();
	  	  	}else if(condition=='+'){
	  	  		$scope.review_Page_no+=1;
	  	  		$scope.getReview();
	  	  	}
	  	  }
	  	 $scope.reviewMore=function(){
	  	 	$scope.review_num=10;
	  	 }
	 	 $scope.FavoritesAdd=function(){
	 	 	if($scope.conllection=="checked"){
	 	 			dataService.favoritesDelete($scope.Favorites.fav_id).then(function(r){
						if(r.Msg){
							helper.myAlert("error:"+r.Msg);
						}else{
							$scope.conllection="default";
							$.toast("取消收藏成功");
							$scope.getFavorites();
						}
					});
	 	 	}else{
	 	 		   var goods={image:$scope.item.img,item_id:$scope.item.item_id,title:$scope.item.name};
	 	 		   var price=[];
	 	 		   async.map($scope.item.skus,function(sku,callback){
	 	 		   		price.push(sku.sku_price);
	 	 		   		callback(null,null);
	 	 		   },function(e,r){
	 	 		   		goods["price"]=_.min(price);
	 	 		   		$rootScope.FavoritesAdd(goods).then(function(r){
					    	if(r.Msg){
			                     helper.myAlert("error:"+r.Msg);
			                }else{
			                	$.toast("收藏成功");
			                    $scope.getFavorites();
			                }
					    });
	 	 		   });
	 	 	}
		  }

		  $scope.skuActionPrice=function(){
		  	$scope.item.stock_num=0;
		  	if(_.size($scope.item.skus)>1){
		  		var sku_price=$scope.item.sku_price||0;

		  		async.map($scope.item.skus,function(sku,callback){
		  			if(sku.sku_checked){
		  				$scope.item.sku_price=sku.sku_price;
		  				$scope.item.sku_stocks=sku.sku_stocks;
		  				$scope.item.sku_properties=sku.sku_properties;
		  			}
		  			$scope.item.stock_num+=sku.sku_stocks
		  			callback(null,null);
		  		},function(e,r){
		  				var price=[];
		  			if(sku_price==0){
		  				$scope.item.sku_stocks=0;

		  				async.map($scope.item.skus,function(sku,call){
		  					price.push(sku.sku_price);
		  					$scope.item.sku_stocks+=sku.sku_stocks;

		  					call(null,null);
		  				},function(ee,rr){
		  					var max_price=_.max(price);
		  					var min_price=_.min(price);
		  					$scope.item.sku_price=min_price+"-"+max_price;
		  					$scope.item.sku_properties=undefined;
		  				});
		  			}else if(sku_price==$scope.item.sku_price&&sku_price!=0){
		  				var statu=true;
		  				$scope.item.sku_stocks=0;
		  				async.map($scope.item.skus,function(sku,call){
		  					price.push(sku.sku_price);
		  					$scope.item.sku_stocks+=sku.sku_stocks;
		  					if(sku.sku_checked){
		  						statu=false;
		  					}
		  					call(null,null);
		  				},function(ee,rr){
		  					if(statu){
		  						var max_price=_.max(price);
			  					var min_price=_.min(price);
		  				

			  					$scope.item.sku_price=min_price+"-"+max_price;
			  					$scope.item.sku_properties=undefined;
		  					}
		  				})
		  			}
		  		});
		  	}else if(_.size($scope.item.skus)==1){
		  		$scope.item.sku_price=$scope.item.skus[0].sku_price;
		  		$scope.item.sku_properties=$scope.item.skus[0].sku_properties;
		  	}
		  	
		  }
		  $scope.sku_checkedBtn=function(typeSet,typeName,checkedName){
		  	console.log("data",$scope.skusPro);
		  	var not_cheked=true;
		  	if(_.size(typeSet.not_cheked)){
		  		not_cheked= _.indexOf(typeSet.not_cheked,checkedName)!=-1;
		  	}
  			if(!not_cheked){
  				return;
  			}
		  	if(typeSet.propertie_checked==checkedName){
		  			typeSet.propertie_checked=null;

		  	}else{
		  		typeSet.propertie_checked=checkedName;
		  		$scope.skus_History.push({typename:typeName,checkedname:checkedName});
		  	}
		 	var checkArray=_.pluck($scope.skusPro,"propertie_checked");
		 	console.log("1111",checkArray);
		 	var type_key_array=_.keys($scope.skusPro);
		 	checkArray=_.without(checkArray,null);
		 	var lastItem={};
		 	var key_find=[];
		 	var y_checkeds=[];
		 	var recursion_key=[];
		 	$scope.item.sku_stocks=0;
		 	async.map($scope.skusPro,function(skuPro,skuProCallback){
		 		if(skuPro.propertie_checked&&checkArray.length<_.size($scope.skusPro)){
		 			if(skuPro.propertie_checked==checkArray[0]){
		 						key_find.push(skuPro.typeName+":"+skuPro.propertie_checked);
		 			}else{
	 					var recursion_status=true;
	 						var key_find_item=key_find.join(";")+";"+skuPro.typeName+":"+skuPro.propertie_checked;
	 						var sku_result= SKUResult[key_find_item];
	 						var checked= $scope.skusPro[skuPro.typeName].propertie_checked;
	 						if(_.size(_.without(sku_result.sku_stock,0))){
	 							recursion_status=false;
		 						key_find.push(skuPro.typeName+":"+skuPro.propertie_checked);
	 							
	 						}else{
	 							$scope.skusPro[skuPro.typeName].propertie_checked=null;
	 						}
		 			}
		 		}else if((skuPro.propertie_checked)&&(checkArray.length==_.size($scope.skusPro))){
		 			var index=_.indexOf(type_key_array,typeName);
		 			async.map(_.first(type_key_array,index+1),function(push_item){
		 				if(skuPro.typeName==push_item){
		 					key_find.push(skuPro.typeName+":"+skuPro.propertie_checked);
		 					recursion_key.push(skuPro.typeName);
		 				}
		 			});
		 		}
		 		if(!skuPro.propertie_checked&&skuPro.not_cheked.length>0){
		 			skuPro.not_cheked=[];
		 		}else if(skuPro.propertie_checked&&skuPro.typeName!=typeName&&skuPro.not_cheked.length>0&&_.findLastIndex($scope.skus_History,{typename:skuPro.typeName})!=-1){
		 			var index=_.indexOf(type_key_array,typeName);
		 			async.map(_.rest(type_key_array,index+1),function(celar_item){
		 				if(skuPro.typeName===celar_item){
		 				 	skuPro.not_cheked=[];
		 				}
		 			})
		 		}
		 		skuProCallback(null,null)
		 	},function(e,r){
		 		if(checkArray.length<_.size($scope.skusPro)){
		 			var mykey_find=_.initial(key_find);
		 			if(mykey_find.length>0){
		 				console.log("key_pro",SKUResult[mykey_find.join(";")].propertie,mykey_find)
		 				async.map(SKUResult[mykey_find.join(";")].propertie,function(propertie,propertieBack){

		 					if($scope.sku_info[propertie].status_id==1&&$scope.sku_info[propertie].sku_stocks>0){
		 						_.map($scope.sku_info[propertie].sku_propertie.split(";"),function(att1){
			 						var status=false;
				 					async.map(mykey_find,function(key,y_checkedBack){
				 						if(key==att1){
				 							status=true;
				 						}else{
				 						}
				 						y_checkedBack(null,null);
				 					},function(ee,rr){
				 						if(!status&&att1){
				 							var att2= att1.split(":");
				 							var att_key=_.difference(key_find,mykey_find)[0].split(":");
				 							if(att2[0]==att_key[0]){
				 								y_checkeds.push(att2[1]);
				 							}
				 						}
				 					});
		 						});
		 					}
		 				});
		 			}
		 		}
		 		console.log("y_checkeds",y_checkeds);
		 		async.map(SKUResult[key_find.join(";")].propertie,function(propertie,propertieBack){
		 			if($scope.sku_info[propertie].status_id==1&&$scope.sku_info[propertie].sku_stocks>0){
		 				$scope.item.sku_stocks+=$scope.sku_info[propertie].sku_stocks;
		 				_.map($scope.sku_info[propertie].sku_propertie.split(";"),function(att1){
		 					var status=false;
		 					async.map(key_find,function(key,y_checkedBack){
		 						if(key==att1){
		 							status=true;
		 						}else{
		 							// console.log("key_att1",att1,$scope.sku_info);
		 						}
		 						y_checkedBack(null,null);
		 					},function(ee,rr){
		 						if(!status){
		 							var att2= att1.split(":");
		 							y_checkeds.push(att2[1]);
		 						}
		 					});
		 				});
		 			}
		 			propertieBack(null,null);
		 		},function(eero,rres){
		 			console.log("禁用项",y_checkeds);
		 			y_checkeds =	_.uniq(y_checkeds);
			 			async.map($scope.skusPro,function(skuPro,recursionBack){
			 				async.map(skuPro.array,function(array){
			 					async.map(y_checkeds,function(y_checked){
			 						if(y_checked==array){
			 							skuPro.not_cheked.push(y_checked);
			 						}
			 					})
			 				});
			 				recursionBack(null,null);
			 			},function(e,r){
			 				if(recursion_key.length>0&&_.difference(type_key_array,recursion_key).length>0&&(checkArray.length==_.size($scope.skusPro))){
			 					var recursion_array=	_.difference(type_key_array,recursion_key);
			 					var recursion_status=true;
			 						var key_find_item="";
			 						if(checkArray.length==_.size($scope.skusPro)){
			 						 key_find_item=key_find.join(";")+";"+recursion_array[0]+":"+$scope.skusPro[recursion_array[0]].propertie_checked;

			 						}
			 						var sku_result= SKUResult[key_find_item];
			 						var checked= $scope.skusPro[recursion_array[0]].propertie_checked;
			 							$scope.skusPro[recursion_array[0]].propertie_checked=null;
				 						if(_.size(_.without(sku_result.sku_stock,0))>0&&recursion_array.length>0){
				 							recursion_status=false;
				 					 	  $scope.sku_checkedBtn($scope.skusPro[recursion_array[0]],$scope.skusPro[recursion_array[0]].typeName,checked);
				 						}
			 				}
			 			});
		 		});
		 	})
		  }
		  $scope.getSkuPrice=function(){
		  	var skusPro_key_array=[];
		  	var sku_price=0;

		  	async.map($scope.skusPro,function(skusPro,skusPro_key_arrayCallback){
		  		if(skusPro.propertie_checked){
		  			skusPro_key_array.push(skusPro.typeName+":"+skusPro.propertie_checked);
		  		}
		  		skusPro_key_arrayCallback(null,null);
		  	},function(e,r){
		  		
		  			var SkuResult=SKUResult[skusPro_key_array.join(";")];
		  			if(SkuResult){
				  		_.map(SkuResult.sku_price,function(skus_price){
				  			if(sku_price<skus_price){
				  				sku_price=skus_price;
				  			}
				  		})
			  		}
		  		// }
		  	});
		  	if(skusPro_key_array.length===_.size($scope.skusPro)){
		  		$scope.item.sku_price= sku_price;
		  	}else if(skusPro_key_array.length<_.size($scope.skusPro)&&skusPro_key_array.length!=0){
		  		$scope.item.sku_price= "0-"+sku_price;
		  	}else{
		  		$scope.skuActionPrice();
		  	}
		  }	
		  var SKUResult = {};
			//获得对象的key
			function getObjKeys(obj) {
			    if (obj !== Object(obj)) throw new TypeError('Invalid object');
			    var keys = [];
			    for (var key in obj)
			        if (Object.prototype.hasOwnProperty.call(obj, key))
			            keys[keys.length] = key;
			    return keys;
			}

			//把组合的key放入结果集SKUResult
			function add2SKUResult(combArrItem, sku) {
				var key = combArrItem.join(";");
			    if(SKUResult[key]) {//SKU信息key属性·
			        SKUResult[key].sku_stocks += sku.sku_stocks;
			        SKUResult[key].sku_price.push(sku.sku_price);
			        SKUResult[key].sku_stock.push(sku.sku_stocks);
			        SKUResult[key].propertie.push(sku.sku_propertie)
			        SKUResult[key].status_id.push(sku.status_id);

			    } else {
			        SKUResult[key] = {
			            sku_stocks : sku.sku_stocks,
			            sku_stock : [sku.sku_stocks],
			            sku_price : [sku.sku_price],
			            status_id:[sku.status_id],
			            propertie : [sku.sku_propertie],
			        };
			    }
			}

			//初始化得到结果集
			function initSKU() {
				console.log("sku_info",$scope.sku_info);
			    var i, j, skuKeys = getObjKeys($scope.sku_info);
			    for(i = 0; i < skuKeys.length; i++) {
			        var skuKey = skuKeys[i];//一条SKU信息key
			        var sku = $scope.sku_info[skuKey];	//一条SKU信息value
			        var skuKeyAttrs = skuKey.split(";"); //SKU信息key属性值数组
			        var len = skuKeyAttrs.length;


			        //对每个SKU信息key属性值进行拆分组合
					var combArr = arrayCombine(skuKeyAttrs);
					for(j = 0; j < combArr.length; j++) {
						add2SKUResult(combArr[j], sku);
					}

			        //结果集接放入SKUResult
			        SKUResult[skuKey] = {
			            sku_stocks:sku.sku_stocks,
			            sku_stock:[sku.sku_stocks],
			            sku_price:[sku.sku_price],
			            status_id:[sku.status_id],
			            propertie:[sku.sku_propertie],
			        }
			    }
			    console.log("222",SKUResult,_.size(SKUResult))
			}

			/**
			 * 从数组中生成指定长度的组合
			 */
			function arrayCombine(targetArr) {
				if(!targetArr || !targetArr.length) {
					return [];
				}

				var len = targetArr.length;
				var resultArrs = [];

				// 所有组合
				for(var n = 1; n < len; n++) {
					var flagArrs = getFlagArrs(len, n);
					while(flagArrs.length) {
						var flagArr = flagArrs.shift();
						var combArr = [];
						for(var i = 0; i < len; i++) {
							flagArr[i] && combArr.push(targetArr[i]);
						}
						resultArrs.push(combArr);
					}
				}
				
				return resultArrs;
			}
			/**
			 * 获得从m中取n的所有组合
			 */
			function getFlagArrs(m, n) {
				if(!n || n < 1) {
					return [];
				}

				var resultArrs = [],
					flagArr = [],
					isEnd = false,
					i, j, leftCnt;

				for (i = 0; i < m; i++) {
					flagArr[i] = i < n ? 1 : 0;
				}

				resultArrs.push(flagArr.concat());

				while (!isEnd) {
					leftCnt = 0;
					for (i = 0; i < m - 1; i++) {
						if (flagArr[i] == 1 && flagArr[i+1] == 0) {
							for(j = 0; j < i; j++) {
								flagArr[j] = j < leftCnt ? 1 : 0;
							}
							flagArr[i] = 0;
							flagArr[i+1] = 1;
							var aTmp = flagArr.concat();
							resultArrs.push(aTmp);
							if(aTmp.slice(-n).join("").indexOf('0') == -1) {
								isEnd = true;
							}
							break;
						}
						flagArr[i] == 1 && leftCnt++;
					}
				}
				return resultArrs;
			} 
		  $scope.checkedClass=function(sku1,skuPro){
		  	// console.log(sku1,skuPro.propertie_checked.indexOf(sku1)===-1);
		  	var checked ="";
		  	if(skuPro.not_cheked.length>0){
		  		// console.log("规格",skuPro);
		  	}
		  	if(skuPro.propertie_checked&&(skuPro.propertie_checked===sku1)){
		  		
		  		checked= "checked";
		  	}else{
		  	 	if(_.size(skuPro.not_cheked)){
		  	 		var disabled_status=false;
		  	 		async.map(skuPro.not_cheked,function(not_cheked,callbck){
		  	 			if(not_cheked==sku1){
		  	 				//只要这个数组里没有这个按钮的值 这个按钮所有关的sku都是没商品
		  	 				disabled_status=true;
		  	 			}
		  	 			callbck(null,null);
		  	 		},function(e,r){
		  	 			if(!disabled_status){
		  	 				checked="not_checked";
		  	 			}
		  	 		})
		  	 	} 
		  	}
		  	return checked;
		  }
		  $scope.disabledProperties=function(propertie,pro){
		  	var style={};
		  	style["background-color"]="#eee";

		  	if(_.size(pro.not_cheked)>0){

		  		_.map(pro.not_cheked,function(propertie_key){
			  		if(propertie_key===propertie){
		  	// console.log(propertie,pro,$scope.skusPro);
		  				// if(_.indexOf(pro.not_cheked,propertie)){
			  				style["background-color"]="#fff";
		  				// }else{
		  				// 	pro.sku_checked=null;
			  			// 	style["background-color"]="#fff";

		  				// }
			  			// return style;
			  		}
			  	})
		  	}else{
		  		style["background-color"]="#fff";
			  			// return style;
		  	}
		  	return style;
		  	// console.log($scope.skusPro);
		  }
		  $scope.closepopup=function(){
		  	$.closePopup();
		  }
		  $scope.Buyimmediately=function(){
			if(_.size($scope.item.skus)>1){
				$scope.BuyimmediatelyPopupButton=true;
				$(".popup-bottom").popup();
			}else{
				$scope.buy_imdy={};
				$scope.buy_imdy["item_id"]=$scope.item.item_id;
				$scope.buy_imdy["sku_id"]=$scope.item.skus[0].sku_id;
				$scope.buy_imdy["quantity"]=$scope.quantity;
				// var buy_imdy={$scope.item.skus[0].sku_id:$scope.item.item_id};
				$location.url("buy/add?buy_imdy="+angular.toJson($scope.buy_imdy));
			}
		  }
		  $scope.Proupconfirm=function(){
		  	var sku_key=""; 
		  	var checked_array= _.pluck($scope.skusPro,"propertie_checked");
			 checked_array= _.without(checked_array,null);
			 if(checked_array.length==_.size($scope.skusPro)){
			 		 var query={};
				    query.query={item_id:$scope.item_id};
				    dataService.itemGet(query).then(function(result){
				    	console.log("result",result);
				 	 	async.map($scope.skusPro,function(skuKey,key_findCallback){
					  		sku_key+=skuKey.typeName+":"+skuKey.propertie_checked+";";
					  		key_findCallback(null,null);
					  	},function(e,r){
			  				 sku_key=sku_key.substring(0,sku_key.length-1);
			  				 console.log("222",$scope.sku_info[sku_key],sku_key);
					  		if($scope.sku_info[sku_key]){
					  			$scope.buy_imdy={};
								$scope.buy_imdy["item_id"]=$scope.item.item_id;
								$scope.buy_imdy["sku_id"]=$scope.sku_info[sku_key].sku_id;
								$scope.buy_imdy["quantity"]=$scope.quantity;
								_.map(result.items[0].skus,function(sku){
									if(sku.sku_id===$scope.buy_imdy["sku_id"]&&$scope.buy_imdy["quantity"]<sku.sku_stocks){
					  					$location.url("buy/add?buy_imdy="+angular.toJson($scope.buy_imdy));
									}else{
										helper.myAlert("购买商品超出卖家库存");
			  							return false;
									}
								});
					  		}
					  	});
			 	 	});
			 }
		  }
		  $scope.cartInit=function(){
		  	if(_.size($scope.item.skus)>1){
		  		$scope.BuyimmediatelyPopupButton=false;
		  		$(".popup-bottom").popup();
		  	}else{
		  		$scope.item.skus[0].sku_checked=true;
		  		$scope.cartAction();
		  	}
		  }
		  $scope.checkedSku=function(){
		  	$scope.BuyimmediatelyPopupButton=undefined;
		  	$(".popup-bottom").popup();
		  }
		  $scope.cartAction=function(){
		  	// var buyer_id=sessionService.get("currentUserInfo").user_id;
		  	var buyer_id =cacheService.get("currentUserInfo").user_id;
		  	var cartstatus=false;//创建还是修改数量
		  	var sku_key="";
		  	var checked_array= _.pluck($scope.skusPro,"propertie_checked");
			 checked_array= _.without(checked_array,null);
			 async.map($scope.skusPro,function(skuKey){
		  		sku_key+=skuKey.typeName+":"+skuKey.propertie_checked+";";
		  	});
			sku_key=sku_key.substring(0,sku_key.length-1);
		  	dataService.cartOne().then(function(carts){
		  		if(carts!=null&&carts.Msg){

		  		}else{
		  			if(_.size(carts.cart_items)==0){
		  				 if(checked_array.length==_.size($scope.skusPro)){
  							$scope.cartShopping(false);
		  				 }else{
		  				 	helper.myAlert("请选择未选完产品规格")
		  				 }
		  			}else{
			  			async.map(carts.cart_items,function(cart,callbackShop){
			  				// if(cart.shop_id==$scope.shop_id){
			  					if(cart.item_id!=$scope.item.item_id){

				  				}else if(cart.item_id==$scope.item.item_id){
				  					if($scope.sku_info[sku_key]&&$scope.sku_info[sku_key].sku_id===cart.sku_id){
				  						cartstatus=true;
				  						$scope.cart=cart;
				  					}
				  					// console.log("追加",$scope.item.skus,cart);
				  					// async.map($scope.item.skus,function(sku){
				  					// 	if(sku.sku_id==cart.sku_id&&sku.sku_checked){
				  					// 		cartstatus=true;
				  					// 		$scope.cart=cart;
				  					// 		console.log($scope.cart)
				  					// 	}else{
				  					// 	}
				  					// })
				  				}
			  				// }else{
			  				// }
			  				callbackShop(null,null);
			  			},function(e,r){
			  				if(cartstatus){
	  							 $scope.cartShopping(true);
	  						}else{
	  							$scope.cartShopping(false);
	  						}
			  			});
		  			}
		  		}
		  	})
		  }
		  $scope.cartShopping=function(status){
		  	if(!status){
		  		var cart={};
			  	// cart.buyer_id=sessionService.get("currentUserInfo").user_id;
			  	// cart.shop_id=$scope.shop_id;
			  	cart.item_id=$scope.item.item_id;
			  	if($scope.item.skus.length==1){
			  		cart.sku_id=$scope.item.skus[0].sku_id;
			  		// cart.price=$scope.item.skus[0].sku_price;
			  	}else{
			  		var sku_key="";
			  	 async.map($scope.skusPro,function(skusPro,sku_back){
			  	 	sku_key+=skusPro.typeName+":"+skusPro.propertie_checked+";";
			  	 	sku_back(null,null)
			  	 },function(){
			  	 	sku_key= sku_key.substring(0,sku_key.length-1);
			  	 	cart.sku_id=$scope.sku_info[sku_key].sku_id;
			  	 });
			  		// _.map($scope.item.skus,function(sku){
			  		// 	if(sku.sku_checked){
			  		// 		cart.sku_id=sku.sku_id;
			  		// 	    // cart.price=sku.sku_price;
			  		// 	}
			  		// });
			  	}
			  	cart.quantity=$scope.quantity;
			  	 var query={};
			  	 var stock_exceed_quota=false;
			    query.query={item_id:$scope.item_id};
			    dataService.itemGet(query).then(function(result){
			    	_.map(result.items[0].skus,function(sku){
						if(sku.sku_id===cart.sku_id&&cart.quantity<sku.sku_stocks){
						}else if(sku.sku_id===cart.sku_id&&cart.quantity>sku.sku_stocks){
							stock_exceed_quota=true;
						}
					});
			    });
			    if(stock_exceed_quota){
			    	helper.myAlert("数量超出了库存");
			  		return
			    }
			  	// if(!cart.buyer_id){
			  	// 	helper.myAlert("请登录");
			  	// 	return
			  	// }
			  	// if(!cart.shop_id){
			  	// 	helper.myAlert("没有找到店铺");
			  	// 	return
			  	// }
			  	if(!cart.item_id){
			  		helper.myAlert("没有找到商品");
			  		return
			  	}

			  	if(!cart.sku_id){
			  		$(".popup-bottom").popup();
			  		return
			  	}
			  	if(!cart.quantity){
			  		helper.myAlert("數量");
			  		return
			  	}
			
			 
			  	$timeout(function(){
			  		cart.total_price=cart.quantity*cart.price;
			  		dataService.cartAdd(cart).then(function(r){
			  			if(r.Msg){
			  				helper.myAlert("error:"+r.Msg);
			  			}else{
			  				$.toast("购物车添加成功");
			  				$scope.closepopup();
			  				$scope.itemAction();
			  			}
			  		});
			  	})
		  	}else{
		  		var data={cart_item_id:$scope.cart.cart_item_id,quantity:$scope.quantity+$scope.cart.quantity};
		  		dataService.cartupdatenum(data).then(function(r){
		  			if(r.Msg){
		  				helper.myAlert("error:"+r.Msg);
		  			}else{
		  				$.toast("购物车添加成功");
		  				$scope.closepopup();
			  			$scope.itemAction();
		  			}
		  		});
		  	}
		  
		  }
		   var slide3 = new auiSlide({
		        container:document.getElementById("aui-slide2"),
		        // "width":300,
		        "height":350,
		        "speed":500,
		        "autoPlay": 3000, //自动播放
		        "loop":true,
		        "pageShow":true,
		        "pageStyle":'dot',
		        'dotPosition':'center',
		    });
		   $scope.openPropup=function(){
		      if($scope.Popup=="block"){
		        $scope.Popup="hide";
		      }else{
		        $scope.Popup="block";
		      }
		}
	    apiready = function(){
	        api.parseTapmode();
	    }
	    // var tab = new auiTab({
	    //     element:document.getElementById("footer")
	    // },function(ret){
	       
	    // });
	    $scope.contactMerchant=function(){
			$rootScope.$broadcast("event:contactBusiness");
			// $("#contactd").popup();
			// $scope.img="/static/uploads/2016-11-24/d95b5a76-c7b0-4151-b671-7ea57524a0e3.jpg";
		}
	    $scope.operatorquantity=function(operator){
	    	if(operator=='+'){

	            $scope.quantity = $scope.quantity+1;
	    	}else if(operator=='-'){
	    		if($scope.quantity>0){
	        	    $scope.quantity = $scope.quantity-1;
	    		}
	    	}
	    }
	    var tab = new auiTab({
	        element:document.getElementById("demo"),
	        index:1,
	        repeatClick:true
	    },function(ret){
	        if(ret.dom.parentNode.getAttribute("type") && ret.dom.parentNode.getAttribute("type")=="count"){
	                    if(ret.index==2)return;
	                    if(ret.index==1){
	                    	$timeout(function(){
	                    	    $scope.quantity = $scope.quantity-1;
	                    	})

	                    }
	                    if(ret.index==3){
	                    	$timeout(function(){
	                  		      $scope.quantity = $scope.quantity+1;
	                    	});
	                    }
	                }
	    });

	}
})();